package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RedisTemplate redisTemplate;
	@RequestMapping("/findUser")
	public List<User> findUser(){
		return userService.findUser();
	}

	@GetMapping("/findAllStr")
	public String findAllStr() throws JsonProcessingException {

		String userStr = (String) redisTemplate.boundValueOps("user363").get();

		if(StringUtils.isEmpty(userStr)){

			List<User> user = userService.findUser();

			log.debug("从数据可以查询的数据"+user.toString());
			ObjectMapper objectMapper = new ObjectMapper();

			userStr= objectMapper.writeValueAsString(user);

			redisTemplate.boundValueOps("user363").set(userStr);
		}

		return userStr;
	}
}
